package com.bigbird.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * 这个只能支持一个客户端连接呢？
 * 因为 serverSocketChannel.accept() 这个是非阻塞 所以主线程会一直跑,读取数据等 来不及接收新的客户端Socket
 */
public class NioServerV1 {
    public static void main(String[] args) throws IOException {
        try(ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()){
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(1881));
            while(true) {
                //这个是非阻塞 所以主线程会一直跑,读取数据等 来不及接收新的客户端Socket
                SocketChannel socketChannel = serverSocketChannel.accept();
                if(null!=socketChannel) {
                    socketChannel.configureBlocking(false);
                    ByteBuffer allocate = ByteBuffer.allocate(20);
                    allocate.put("hello connection".getBytes(UTF_8));
                    socketChannel.write(allocate);
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    while (socketChannel.read(byteBuffer) > -1) {
                        byteBuffer.flip();
                        while(byteBuffer.hasRemaining()){
                            int remaining = byteBuffer.remaining();
                            byte[] bytes=new byte[remaining];
                            byteBuffer.get(bytes);
                            System.out.println(" message :: "+new String(bytes));
                        }
                        byteBuffer.clear();
                    }
                }
            }
        }

    }
}
